import { AssetInfo } from "../@types/packages/asset-db/@types/public";
import { exists, mkdir,readFile,writeFile } from "./utils/mfs";
import Path from "path";
const mvc_config = require("../template/mvc_config.json");


export function createMVC(assetInfo: AssetInfo, type:string) {
    console.log(`create ${type}`);
    const lowerCaseType = type.toLowerCase();
    const prefabName = getAssetNameNoExt(assetInfo);
    const fileName = `${type}${prefabName}.ts`;


    const moduleName = getModuleName(assetInfo);
    const dirPath = `${Editor.Project.path}/${mvc_config.mvc_dir}/${moduleName}/${lowerCaseType}`;
    if (!exists(Path.join(dirPath))) {
        if (!mkdir(Path.join(dirPath))) {
            console.log("路径不存在,创建失败",dirPath)
            return;
        }
    }

    const fullPath = `${dirPath}/${fileName}`;
    if (exists(Path.join(fullPath))) {
        console.log("文件已存在,不再创建",fullPath);
        return;
    }
    const customTempPath = `${Editor.Project.path}/extensions/mvc_creator/template/${lowerCaseType}_template_custom`;
    const tempPath = `${Editor.Project.path}/extensions/mvc_creator/template/${lowerCaseType}_template`;
    let data = exists(Path.join(customTempPath)) ? readFile(Path.join(customTempPath),'utf-8') : readFile(Path.join(tempPath),'utf-8');    
    data = data.replace(/__VIEW_CLASS_NAME/g, `View${prefabName}`);
    data = data.replace(/__CTRL_CLASS_NAME/g, `VC${prefabName}`);
    data = data.replace(/__MODEL_CLASS_NAME/g, `Model${prefabName}`);
    data = data.replace(/__PREFAB_PATH/g, `game/prefab/mvc/${moduleName}/${prefabName}`);
    writeFile(Path.join(fullPath),data,'utf-8');
    console.log("文件创建成功:", fullPath);
}


function getAssetNameNoExt(assetInfo: AssetInfo) {
    return Editor.Utils.Path.basenameNoExt(assetInfo.name);
}

function getModuleName(assetInfo: AssetInfo) {
    const url = assetInfo.url;
    return Editor.Utils.Path.basenameNoExt(Editor.Utils.Path.dirname(url));
}
